package com.xja.security.service.impl;

import com.xja.security.entity.Admin;
import com.xja.security.service.AdminService;
import com.xja.security.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserDetailServiceImpl
 * @Description
 * @Author MaYu
 * @Date 2022/4/12 14:51
 * @Version 1.0
 **/
@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Admin admin = adminService.login(username);
        if (admin == null){
            throw new UsernameNotFoundException("用户名错误");
        }

        List<String> roleList = roleService.findRoleByAid(admin.getaId());
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        for (String role : roleList) {
            authorityList.add(new SimpleGrantedAuthority(role));
        }
        return new User(username, admin.getaPass(), authorityList);
    }
}
